const crypto = require("crypto");

/**
 * 将URL参数字符串转换为对象
 * @param {string} queryString - URL参数字符串
 * @returns {Object} 参数对象
 */
function parseQueryString(queryString) {
	if (!queryString) return {};

	return queryString.split("&").reduce((params, param) => {
		const [key, value] = param.split("=");
		params[key] = value;
		return params;
	}, {});
}

// 获取完整的请求参数
function getFullParams(params, signature) {
	const paramsObj =
		typeof params === "string" ? parseQueryString(params) : params;
	return {
		...paramsObj,
		SignatureMD5: signature,
	};
}

/**
 * 生成MD5签名
 * @param {Object|string} params - 参数对象或URL参数字符串
 * @returns {string} MD5签名
 */
function generateSignatureMD5(params) {
	// 如果传入的是字符串，则解析为对象
	const paramsObj =
		typeof params === "string" ? parseQueryString(params) : params;
	// paramsObj.SignatureStamp = new Date().getTime().toString()
	// console.log("paramsObj", paramsObj);
	
	// 1. 按照字母顺序排列参数
	const orderedParams = {};
	Object.keys(paramsObj)
		.sort()
		.forEach((key) => {
			orderedParams[key] = paramsObj[key];
		});



	// 2. 拼接 key=value 字符串
	const kvPairs = Object.entries(orderedParams).map(([key, value]) => {
		if (typeof value === "object") value = JSON.stringify(value);
		return `${key}=${value}`;
	});

	// 3. 拼接字符串并加密钥
	const str =
		kvPairs.join("&").toLowerCase() + "053ef899Af294A36bB5ae1730c7995E8";

	// 4. 计算 MD5
	const signature = crypto.createHash("md5").update(str).digest("hex");

	return Object.entries(getFullParams(paramsObj, signature))
		.map(([k, v]) => `${k}=${v}`)
		.join("&")
}

module.exports = generateSignatureMD5